package test;

public class SellTicketWithBlock implements Runnable{
    //总共有100张票,票数是一个共享资源，被多个售票窗口（线程）共享
    private volatile int tickets = 100;
    private final Object lock = new Object();

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        while (tickets>0){
           synchronized (lock){
               if (tickets>0){
                   System.out.println(name + "窗口售出的一张票：" + tickets);
                   tickets--;
               }else{
                   System.out.println("当前线程：" + name + "，没有机会得到执行");
               }
               try {
                   Thread.sleep(1);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
       }
    }

    public static void main(String[] args) {
        Runnable sellTicket=new SellTicketWithBlock();
        Thread a=new Thread(sellTicket,"A");
        Thread b=new Thread(sellTicket,"B");
        Thread c=new Thread(sellTicket,"C");
        Thread d=new Thread(sellTicket,"D");
        a.start();
        b.start();
        c.start();
        d.start();
    }
}
